import java.io.*;

import lejos.pc.comm.*;

public class BluetoothConnection {

	private NXTConnector connection;
	private boolean connected;
	private DataOutputStream dos;
	private DataInputStream dis;

	public BluetoothConnection() {
		connection = null;
		connected = false;
		dos = null;
		dis = null;
	}

	public void waitforbtconnection(String name) {
		connection = new NXTConnector();
		connection.connectTo("btspp://" + name);
		System.out.println("Connected to NXT!");
		dos = new DataOutputStream(connection.getOutputStream());
		dis = new DataInputStream(connection.getInputStream());
		this.connected = true;
	}

	/*
	 * public String nextXML() {
	 * 
	 * return null; }
	 */
	
	public String recieveData() throws IOException {
		StringBuilder buffer = new StringBuilder();

		while (buffer.length() == 0) {
			buffer.append(dis.readUTF().trim());
		}

		return buffer.toString();
	}

	public NXTConnector getConnection() {
		return this.connection;
	}
	
	public boolean isConnected() //ADDED FUNCTION! how can we check if its connected? NXTConnector doesn't seem to come with something like .isConnected() 
	{
		return this.connected;
	}

	public void closeConnection() {
		try {
			dis.close();
			dos.close();
			connection.close();
			connected = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(String data) throws IOException {
		this.dos.writeUTF(data);
		this.dos.flush();
	}

}
